package cn.itsource.ymcc.service.impl;

import cn.itsource.result.JSONResult;
import cn.itsource.util.AssertUtil;
import cn.itsource.util.HttpUtil;
import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.dto.LoginDto;
import cn.itsource.ymcc.dto.RefreshDto;
import cn.itsource.ymcc.mapper.LoginMapper;
import cn.itsource.ymcc.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author Cherish
 * @since 2022-08-05
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    private static final String TOKEN_URL = "http://localhost:10030/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&redirect_uri=http://www.baidu.com&password=%s";


    private static final String REFRESHTOKEN_URL = "http://localhost:10030/oauth/token?grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s";

    @Override
    public JSONResult loginCommon(LoginDto dto) {
        int type = dto.getType().intValue();
        String clientId = null;
        String secret = null;
        if(type == 0){//管理端
            clientId="admin";
            secret="123";
        }else if(type == 1){
            clientId="website";
            secret="123";
        }
        AssertUtil.isNotNull(clientId,"非法请求！！");
        String tokenURL = String.format(TOKEN_URL,clientId,secret,dto.getUsername(),dto.getPassword());
        String result = HttpUtil.sendPost(tokenURL, null);
        Map map = JSONObject.parseObject(result, Map.class);
        if(result.contains("error_description")){
            return JSONResult.error("用户名密码错误！！");
        }else{
            long timeOut = System.currentTimeMillis() + Long.valueOf(map.get("expires_in").toString());
            map.put("expiresTime",timeOut);
            return JSONResult.success(map);
        }

    }

    @Override
    public JSONResult refreshToken(RefreshDto dto) {

        int type = dto.getType().intValue();
        String clientId = null;
        String secret = null;
        if(type == 0){//管理端
            clientId="admin";
            secret="123";
        }else if(type == 1){
            clientId="website";
            secret="123";
        }
        AssertUtil.isNotNull(clientId,"非法请求！！");
        String tokenURL = String.format(REFRESHTOKEN_URL,dto.getRefreshToken(),clientId,secret);
        String result = HttpUtil.sendPost(tokenURL, null);
        Map map = JSONObject.parseObject(result, Map.class);
        long timeOut = System.currentTimeMillis() + Long.valueOf(map.get("expires_in").toString());
        map.put("expiresTime",timeOut);
        return JSONResult.success(map);
    }
}
